package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.utils.AliOssUtil;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Transactional
    @Override
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        String url = aliOssUtil.upload(dishDTO.getImage().getBytes(), dish.getName());
        log.info("上传成功，图片地址为：{}", url);
        dishMapper.insert(dish);
        log.info("保存菜品信息：{}", dish);

        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //等同于flavors != null && flavors.size() > 0
        if (!CollectionUtils.isEmpty(flavors)) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
//批量插入菜品口味数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        List<DishVO> list = dishMapper.list(dishPageQueryDTO);
        Page<DishVO> p = (Page<DishVO>) list;
        return new PageResult(p.getTotal(), p.getResult());
    }

    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否能被删除？状态是否为禁用

        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE)
                //商品起售中不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //判断当前菜品是否被套餐关联
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (!CollectionUtils.isEmpty(setmealIds))
            //该菜品被套餐关联
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);

        //删除菜品和对应口味
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    @Override
    public DishVO getByIdWithFlavors(long id) {


        Dish dish = dishMapper.getById(id);
        List<DishFlavor> list = dishFlavorMapper.getByDishId(id);

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);

        dishVO.setFlavors(list);
        return dishVO;
    }

    @Override
    public void update(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.update(dish);

        // 删除口味
        Long dishId = dishDTO.getId();
        dishFlavorMapper.deleteByDishId(dishId);

        //新增口味道
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (!CollectionUtils.isEmpty(flavors)) {
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    public List<Dish> getByCategoryId(long categoryId) {
        return dishMapper.getByCategoryId(categoryId);
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();

        dishMapper.update(dish);
    }

    @Override
    public List<DishVO> listWithFlavors(Long categoryId) {
        // 1. 一次性从数据库查询出所有需要的信息（菜品+分类名）
        List<DishVO> dishVOList = dishMapper.listWithCategoryName(categoryId);

        // 2. 如果需要加载口味，再进行处理
        // 注意：加载口味也会有N+1问题，需要用in查询等方式优化
        for (DishVO dishVO : dishVOList) {
            // 根据dishVO.getId()去查询口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(dishVO.getId());
            dishVO.setFlavors(flavors);
        }

        return dishVOList;
    }
}
